<template>
  <el-card>
    <template #header>商品添加</template>

    <el-form
      :model="goodsForm"
      :rules="rules"
      ref="ruleForm"
      label-width="100px"
      class="demo-ruleForm"
      size="mini"
    >
      <el-form-item label="商品名称" prop="name">
        <el-input v-model="goodsForm.name"></el-input>
      </el-form-item>
      <el-form-item label="商品分类" prop="cate">
        <el-select v-model="goodsForm.cate" placeholder="请选择商品分类">
          <el-option
            v-for="(item, i) in cates"
            :key="i"
            :label="item.cateName"
            :value="item.cateName"
          ></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="商品价格">
        <!-- 步进器 -->
        <el-input-number v-model="goodsForm.price" :min="0"></el-input-number>
      </el-form-item>

      <el-form-item label="商品图片" prop="type">
        <!-- 上传组件 -->
        <el-upload
          class="avatar-uploader"
          action="http://39.106.222.189:5000/goods/goods_img_upload"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
        >
          <img v-if="imageUrl" :src="imageUrl" class="avatar" />
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>

      <el-form-item label="商品描述" prop="desc">
        <el-input type="textarea" v-model="goodsForm.desc"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm('ruleForm')"
          >确认添加</el-button
        >
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script>
import { getAllCate } from '@/api/cate.js'
import { addGoods } from '@/api/goods.js'

export default {
  data() {
    return {
      goodsForm: {
        name: '',
        cate: '',
        price: '',
        imgUrl: '',
        desc: ''
      },
      rules: {
        name: [
          { required: true, message: '请输入商品名称', trigger: 'blur' },
          { min: 2, max: 8, message: '长度在 2 到 8 个字符', trigger: 'blur' }
        ],
        cate: [
          { required: true, message: '请选择商品分类', trigger: 'change' }
        ],
        desc: [{ required: true, message: '请填写活动描述', trigger: 'blur' }]
      },
      // 本地预览图片的地址
      imageUrl: '',
      cates: []
    }
  },
  created() {
    this.getcates()
  },
  methods: {
    async getcates() {
      const { categories } = await getAllCate()
      // console.log(categories)
      this.cates = categories
    },
    submitForm(formName) {
      this.$refs[formName].validate(async valid => {
        if (valid) {
          // 如果商品价格是0， 或者图片没有上传则不会请求
          if (this.goodsForm.price === 0 || this.goodsForm.imgUrl === '') {
            return this.$message.error('请填写完整的表单')
          }
          // 表单都有内容了，再发请求
          const { code } = await addGoods({
            name: this.goodsForm.name,
            category: this.goodsForm.cate,
            price: this.goodsForm.price,
            imgUrl: this.goodsForm.imgUrl,
            goodsDesc: this.goodsForm.desc
          })
          if (code === 0) {
            setTimeout(() => {
              this.$router.push('/goods/list')
            }, 1000)
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    resetForm(formName) {
      this.$refs[formName].resetFields()
    },
    handleAvatarSuccess(res, file) {
      // 能够实现本地的预览
      this.imageUrl = URL.createObjectURL(file.raw)

      //  res指的是响应结果
      this.goodsForm.imgUrl = res.imgUrl
    },
    beforeAvatarUpload(file) {
      // 规定死了只能是 jpeg 格式，需要一个布尔值的结果
      // const isJPG = file.type === 'image/jpeg'
      // 数组有一个是否包含的方法   includes
      const arr = [
        'image/jpeg',
        'image/png',
        'image/jpg',
        'image/webp',
        'image/gif'
      ]
      const isJPG = arr.includes(file.type)
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    }
  }
}
</script>

<style lang="less" scoped>
.el-input,
.el-select {
  width: 197px;
}

// 穿刺
/deep/textarea {
  width: 300px;
  height: 130px;
  resize: none;
}

/deep/.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  margin-top: 20px;
}
/deep/.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 128px;
  height: 128px;
  line-height: 128px;
  text-align: center;
}
.avatar {
  width: 128px;
  height: 128px;
  display: block;
}
</style>
